package br.com.analiz.bean;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlCommandLink;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import br.com.analiz.dao.UserDao;
import br.com.analiz.model.User;

@ManagedBean(name = "userBean")
@SessionScoped
public class UserBean {

	UserDao userDao = new UserDao();
	User user;
	List<User> users;
	User[] selectedUsers;

	public UserBean() {
		System.out.println("FOI NO CONSTRUTOR USUARIO");
		user = new User();
		users = new ArrayList<User>();
		users = userDao.findAll();
		
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUsers() {
		return this.users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public User[] getSelectedUsers() {
		return selectedUsers;
	}

	public void setSelectedUsers( User[] selectedUsers) {
		
		
		
		for (int i = 0; i < selectedUsers.length; i++) {
			System.out.println(selectedUsers[i].getUser());
			System.out.println("Selecionou");
		}
		this.selectedUsers = selectedUsers;
	}

	public String saveUpdate(ActionEvent event) {
		
		HtmlCommandLink link = (HtmlCommandLink) event.getSource();
		System.out.println(link.getValue().toString()); 
		
		//userDao.save(user);
		users = new ArrayList<User>();
		users = userDao.findAll();
		return "sucess";

	}
	
	public String delete(){
		
		for (int i = 0; i < this.selectedUsers.length; i++) {
			if(this.users.contains(this.selectedUsers[i])){
				this.users.remove(this.selectedUsers[i]);
				userDao.delete(this.selectedUsers[i]);
			}
			
		}
		
		return "sucess";
	}

	public String logar() {

		if (!userDao.findUsuario(user.getUser(), user.getSenha()).isEmpty()) {
			System.out.println("LOGOU");
			return "success";

		} else {
			System.out.println("NAO LOGOU");
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"User or Password Invalid", ""));
			return "fail";

		}

	}

}
